package cn.stylefeng.guns.modular.tool.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.AreaId;
import cn.stylefeng.guns.core.util.justGetXSCKDApi;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPositionParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicPositionResult;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicGoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicPositionService;
import cn.stylefeng.guns.modular.tool.entity.ToolWave;
import cn.stylefeng.guns.modular.tool.entity.ToolWork;
import cn.stylefeng.guns.modular.tool.model.params.ToolBasicPackInstallParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolExpressExcelParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolExpressParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolExpressScanParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolExpressSumParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolGoodsInstallParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolTaskArrangeParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolWorkParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolWorkTaskParam;
import cn.stylefeng.guns.modular.tool.model.result.ToolBasicPackInstallResult;
import cn.stylefeng.guns.modular.tool.model.result.ToolExpressExcelResult;
import cn.stylefeng.guns.modular.tool.model.result.ToolExpressResult;
import cn.stylefeng.guns.modular.tool.model.result.ToolGoodsInstallResult;
import cn.stylefeng.guns.modular.tool.model.result.ToolTaskArrangeResult;
import cn.stylefeng.guns.modular.tool.model.result.ToolWorkResult;
import cn.stylefeng.guns.modular.tool.model.result.ToolWorkTaskResult;
import cn.stylefeng.guns.modular.tool.service.ToolBasicPackInstallService;
import cn.stylefeng.guns.modular.tool.service.ToolExpressExcelService;
import cn.stylefeng.guns.modular.tool.service.ToolExpressScanService;
import cn.stylefeng.guns.modular.tool.service.ToolExpressService;
import cn.stylefeng.guns.modular.tool.service.ToolExpressSumService;
import cn.stylefeng.guns.modular.tool.service.ToolGoodsInstallService;
import cn.stylefeng.guns.modular.tool.service.ToolTaskArrangeService;
import cn.stylefeng.guns.modular.tool.service.ToolWaveService;
import cn.stylefeng.guns.modular.tool.service.ToolWorkService;
import cn.stylefeng.guns.modular.tool.service.ToolWorkTaskService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;


/**
 * 云仓派工表控制器
 * @author zhucx
 * @Date 2023-04-18 10:49:27
 */
@Controller
@RequestMapping("/toolWork")
public class ToolWorkController extends BaseController {

    private String PREFIX = "/tool/toolWork";

    @Autowired
    private ToolWorkService toolWorkService;

    @Autowired
    private UserService userService;

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private ToolBasicPackInstallService toolBasicPackInstallService;

    @Autowired
    private ToolWaveService toolWaveService;
    
    private Lock lock = new ReentrantLock();

    /**
     * 跳转到主页面
     *
     * @author zhucx
     * @Date 2023-04-18
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/toolWork.html";
    }

    /**
     * 生成波次页面
     * @author zhucx
     * @Date 2023-04-18
     */
    @RequestMapping("/toWork")
    public String toWork(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	ToolBasicPackInstallParam packInstallParam = new ToolBasicPackInstallParam();
    	packInstallParam.setDeptId(deptId);
    	List<ToolBasicPackInstallResult> pilist = toolBasicPackInstallService.findListBySpec(packInstallParam, user.getOperateId());
    	model.addAttribute("pilist", pilist);
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        BasicPositionParam positionParam = new BasicPositionParam();
        positionParam.setPositionAreaId(AreaId.arrangeAreaId);
        List<BasicPositionResult> positionlist = basicPositionService.findListBySpec(positionParam, null, null, null, null);
    	model.addAttribute("positionlist", positionlist);
        return PREFIX + "/toolWork_add.html";
    }

    /**
     * 编辑页面
     *
     * @author zhucx
     * @Date 2023-04-18
     */
    @RequestMapping("/editWellen")
    public String editWellen(Model model,Long waveId) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	ToolBasicPackInstallParam packInstallParam = new ToolBasicPackInstallParam();
    	packInstallParam.setDeptId(deptId);
    	List<ToolBasicPackInstallResult> pilist = toolBasicPackInstallService.findListBySpec(packInstallParam, user.getOperateId());
    	model.addAttribute("pilist", pilist);
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/toolWork_edit.html";
    }

    /**
     * 选择小组页面
     *
     * @author zhucx
     * @Date 2023-04-18
     */
    @RequestMapping("/choice_user")
    public String choice_user(Model model) {
        BasicPositionParam positionParam = new BasicPositionParam();
        positionParam.setPositionAreaId(AreaId.arrangeAreaId);
        List<BasicPositionResult> positionlist = basicPositionService.findListBySpec(positionParam, null, null, null, null);
    	model.addAttribute("positionlist", positionlist);
        return PREFIX + "/choice_user.html";
    }
    
    /**
     * 保存波次
     * @throws InterruptedException 
     */
    @RequestMapping("/saveItem")
    @ResponseBody
	@Transactional(rollbackFor = Exception.class,timeout = 600)
    public ResponseData saveItem(ToolWorkParam toolWorkParam,String orderNumber) throws InterruptedException {
    	User user = userService.getcurrentUser();
    	ResponseData resdata = new ResponseData();
    	resdata.setSuccess(true);
    	
    	if(ToolUtil.isEmpty(orderNumber)) {
    		return ResponseData.error("快递单号不得为空");
    	}
    	
    	BasicCustomer basicCustomer = basicCustomerService.getById(toolWorkParam.getCustomerId());
    	if(ToolUtil.isEmpty(basicCustomer.getJustAppkey())) {
    		return ResponseData.error("请添加客户聚水潭appKey");
    	} 
    	if(ToolUtil.isEmpty(basicCustomer.getJustAppsecret())) {
    		return ResponseData.error("请添加客户聚水潭appSecret");
    	} 
    	if(ToolUtil.isEmpty(basicCustomer.getAccessTokenme())) {
    		return ResponseData.error("请添加我方聚水潭授权码");
    	} 
    	if(ToolUtil.isEmpty(basicCustomer.getOwnercoId())) {
    		return ResponseData.error("请添加客户聚水潭货主编码");
    	} 
    	
    	String[] strs = orderNumber.split("\n");//快递单号
    	List<String> l_ids = new ArrayList<>();
    	
		lock.lock();//获取锁
		try {
			List<ToolExpressExcelParam> list = new ArrayList<ToolExpressExcelParam>();
			for (int i = 0; i < strs.length; i++) {
				l_ids.add("'"+strs[i]+"'");
				if (l_ids.size() == 20) {//最多20个快递单号获取一次
					//接口调用频率秒级内不超过5次，分钟内不超过100次
					String data = justGetXSCKDApi.getSellerItem(basicCustomer.getJustAppkey(),basicCustomer.getJustAppsecret(),basicCustomer.getAccessTokenme(), l_ids, basicCustomer.getOwnercoId());
					JSONObject jsonObject = new JSONObject(data);
					if(jsonObject.get("code").toString().equals("0")) {
						JSONObject jsonObject1 = new JSONObject(jsonObject.get("data").toString());
						if(Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {
							JSONArray jsonArray = new JSONArray(jsonObject1.get("datas").toString());
							for (Object object : jsonArray) {
								JSONObject jsonObject2 = new JSONObject(object.toString());
								JSONArray jsonArray1 = new JSONArray(jsonObject2.get("items").toString());
								for (Object object1 : jsonArray1) {
									JSONObject jsonObject3 = new JSONObject(object1.toString());
									ToolExpressExcelParam toolExpressExcelParam = new ToolExpressExcelParam();
									toolExpressExcelParam.setWaveId(toolWorkParam.getWaveId());
									toolExpressExcelParam.setWellen(toolWorkParam.getWellen());
									toolExpressExcelParam.setCustomerId(toolWorkParam.getCustomerId());
									toolExpressExcelParam.setCustomerName(basicCustomer.getCustomerName());
									toolExpressExcelParam.setDeptId(user.getDeptId());
									
									String sku_id = jsonObject3.get("sku_id").toString();
									if (ToolUtil.isNotEmpty(sku_id)) {
										if(sku_id.equals("null")||sku_id.equals("1759947952444423")||sku_id.equals("1759325202211891")||sku_id.equals("4967199140507")||sku_id.equals("1759325202211890")
												||sku_id.equals("1759947952444420")||sku_id.equals("687374017518")||sku_id.equals("693717971892")
												||sku_id.equals("caixiang")
												||sku_id.equals("qipaodai-05")
												||sku_id.equals("goodcard5")
												||sku_id.equals("goodcard2")
												||sku_id.equals("TM-R0")||sku_id.equals("TM-NK")
												||sku_id.equals("TM-RO")
												||sku_id.equals("zhixiang")||sku_id.equals("zhixiang-A1")||sku_id.equals("zhixiang-A3")
												||sku_id.equals("会员福利卡")||sku_id.equals("瑜大公子卡片")||sku_id.equals("纸箱包装")) {
											continue;
										}
										toolExpressExcelParam.setGoodsNumber(sku_id);//商品编号
									}
									
									String num = jsonObject3.get("qty").toString();
									if (ToolUtil.isNotEmpty(num)) {
										if(num.equals("null")) {
											continue;
										} else {
											toolExpressExcelParam.setNum(num);//数量
										}
									} else {
										continue;
									}
									
									String v1 = jsonObject2.get("io_id").toString();
									if (ToolUtil.isNotEmpty(v1)) {
										if(!v1.equals("null")) {
											toolExpressExcelParam.setOutNumber(v1);//出库单号
										} else {
											continue;
										}
									} else {
										continue;
									}
									
									String  l_id = jsonObject2.get("l_id").toString();
									if (ToolUtil.isNotEmpty(l_id)) {
										if(!l_id.equals("null")) {
											toolExpressExcelParam.setOrderNumber(l_id);//快递单号
										} 
									}
									
									String v2 = jsonObject2.get("logistics_company").toString();
									if (ToolUtil.isNotEmpty(v2)) {
										if(!v2.equals("null")) {
											toolExpressExcelParam.setV2(v2);//快递公司
										} 
									}
									
									String v3 = jsonObject2.get("receiver_state").toString();
									if (ToolUtil.isNotEmpty(v3)) {
										if(!v3.equals("null")) {
											toolExpressExcelParam.setV3(v3);//省份
										} 
									}
									
									String v4 = jsonObject2.get("receiver_city").toString();
									if (ToolUtil.isNotEmpty(v4)) {
										if(!v4.equals("null")) {
											toolExpressExcelParam.setV4(v4);//城市
										} 
									}
									
									String v5 = jsonObject2.get("receiver_district").toString();
									if (ToolUtil.isNotEmpty(v5)) {
										if(!v5.equals("null")) {
											toolExpressExcelParam.setV5(v5);//区县
										} 
									}
									
									String v6 = jsonObject2.get("receiver_town").toString();
									if (ToolUtil.isNotEmpty(v6)) {
										if(!v6.equals("null")) {
											toolExpressExcelParam.setV6(v6);//街道
										} 
									}
									
									String v7 = "";
									if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV3())) {
										v7 += toolExpressExcelParam.getV3();
										if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV4())) {
											v7 += toolExpressExcelParam.getV4();
											if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV5())) {
												v7 += toolExpressExcelParam.getV5();
												if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV6())) {
													v7 += toolExpressExcelParam.getV6();
												}
											}
										}
									}
									toolExpressExcelParam.setV7(v7);
									
									list.add(toolExpressExcelParam);
								}
							}
						} else {
							resdata.setSuccess(false);
							resdata.setMessage("未获取到快递明细");
						}
					} else {
						resdata.setSuccess(false);
						resdata.setMessage("拉取失败！"+data);
					}
					if((i+1) < strs.length) {
						Thread.currentThread().sleep(210);//如果有下一页 等待0.21秒
					}
					l_ids = new ArrayList<>();
				}
			}
			
			if(l_ids.size() > 0) {
				String data = justGetXSCKDApi.getSellerItem(basicCustomer.getJustAppkey(),basicCustomer.getJustAppsecret(),basicCustomer.getAccessTokenme(), l_ids, basicCustomer.getOwnercoId());
				JSONObject jsonObject = new JSONObject(data);
				if(jsonObject.get("code").toString().equals("0")) {
					JSONObject jsonObject1 = new JSONObject(jsonObject.get("data").toString());
					if(Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {
						JSONArray jsonArray = new JSONArray(jsonObject1.get("datas").toString());
						for (Object object : jsonArray) {
							JSONObject jsonObject2 = new JSONObject(object.toString());
							JSONArray jsonArray1 = new JSONArray(jsonObject2.get("items").toString());
							for (Object object1 : jsonArray1) {
								JSONObject jsonObject3 = new JSONObject(object1.toString());
								ToolExpressExcelParam toolExpressExcelParam = new ToolExpressExcelParam();
								toolExpressExcelParam.setWaveId(toolWorkParam.getWaveId());
								toolExpressExcelParam.setWellen(toolWorkParam.getWellen());
								toolExpressExcelParam.setCustomerId(toolWorkParam.getCustomerId());
								toolExpressExcelParam.setCustomerName(basicCustomer.getCustomerName());
								toolExpressExcelParam.setDeptId(user.getDeptId());
								
								String sku_id = jsonObject3.get("sku_id").toString();
								if (ToolUtil.isNotEmpty(sku_id)) {
									if(sku_id.equals("null")||sku_id.equals("1759947952444423")||sku_id.equals("1759325202211891")||sku_id.equals("4967199140507")||sku_id.equals("1759325202211890")
											||sku_id.equals("1759947952444420")||sku_id.equals("687374017518")||sku_id.equals("693717971892")
											||sku_id.equals("caixiang")
											||sku_id.equals("qipaodai-05")
											||sku_id.equals("goodcard5")
											||sku_id.equals("goodcard2")
											||sku_id.equals("TM-R0")||sku_id.equals("TM-NK")
											||sku_id.equals("TM-RO")
											||sku_id.equals("zhixiang")||sku_id.equals("zhixiang-A1")||sku_id.equals("zhixiang-A3")
											||sku_id.equals("会员福利卡")||sku_id.equals("瑜大公子卡片")||sku_id.equals("纸箱包装")) {
										continue;
									}
									toolExpressExcelParam.setGoodsNumber(sku_id);//商品编号
								}
								
								String num = jsonObject3.get("qty").toString();
								if (ToolUtil.isNotEmpty(num)) {
									if(num.equals("null")) {
										continue;
									} else {
										toolExpressExcelParam.setNum(num);//数量
									}
								} else {
									continue;
								}
								
								String v1 = jsonObject2.get("io_id").toString();
								if (ToolUtil.isNotEmpty(v1)) {
									if(!v1.equals("null")) {
										toolExpressExcelParam.setOutNumber(v1);//出库单号
									} else {
										continue;
									}
								} else {
									continue;
								}
								
								String  l_id = jsonObject2.get("l_id").toString();
								if (ToolUtil.isNotEmpty(l_id)) {
									if(!l_id.equals("null")) {
										toolExpressExcelParam.setOrderNumber(l_id);//快递单号
									} 
								}
								
								String v2 = jsonObject2.get("logistics_company").toString();
								if (ToolUtil.isNotEmpty(v2)) {
									if(!v2.equals("null")) {
										toolExpressExcelParam.setV2(v2);//快递公司
									} 
								}
								
								String v3 = jsonObject2.get("receiver_state").toString();
								if (ToolUtil.isNotEmpty(v3)) {
									if(!v3.equals("null")) {
										toolExpressExcelParam.setV3(v3);//省份
									} 
								}
								
								String v4 = jsonObject2.get("receiver_city").toString();
								if (ToolUtil.isNotEmpty(v4)) {
									if(!v4.equals("null")) {
										toolExpressExcelParam.setV4(v4);//城市
									} 
								}
								
								String v5 = jsonObject2.get("receiver_district").toString();
								if (ToolUtil.isNotEmpty(v5)) {
									if(!v5.equals("null")) {
										toolExpressExcelParam.setV5(v5);//区县
									} 
								}
								
								String v6 = jsonObject2.get("receiver_town").toString();
								if (ToolUtil.isNotEmpty(v6)) {
									if(!v6.equals("null")) {
										toolExpressExcelParam.setV6(v6);//街道
									} 
								}
								
								String v7 = "";
								if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV3())) {
									v7 += toolExpressExcelParam.getV3();
									if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV4())) {
										v7 += toolExpressExcelParam.getV4();
										if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV5())) {
											v7 += toolExpressExcelParam.getV5();
											if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV6())) {
												v7 += toolExpressExcelParam.getV6();
											}
										}
									}
								}
								toolExpressExcelParam.setV7(v7);
								
								list.add(toolExpressExcelParam);
							}
						}
					} else {
						resdata.setSuccess(false);
						resdata.setMessage("未获取到快递明细");
					}
				} else {
					resdata.setSuccess(false);
					resdata.setMessage("拉取失败！"+data);
				}
			}
			
			if(list.size()>0) {
		        toolExpressExcelService.saveBatchList(list);

				List<ToolExpressParam> listadd = new ArrayList<ToolExpressParam>();
		        for (ToolExpressExcelParam p : list) {
					boolean order = false;
					for (int i = 0; i < listadd.size(); i++) {
						if(listadd.get(i).getV1().equals(p.getOutNumber())) {
							order = true;
							boolean goods = false;
							for (ToolExpressParam tp2 : listadd.get(i).getList()) {
								if(tp2.getGoodsNumber().equals(p.getGoodsNumber())){
									goods = true;
									BigDecimal num = new BigDecimal(tp2.getNum());
									BigDecimal nump = new BigDecimal(p.getNum());
									tp2.setNum(num.add(nump)+"");
									break;
								}
							}
							if(!goods) {
								ToolExpressParam pnew = new ToolExpressParam();
								pnew.setGoodsNumber(p.getGoodsNumber());
								pnew.setNum(p.getNum());
								listadd.get(i).getList().add(pnew);
								break;
							} else {
								break;
							}
						}
					}
					if(!order) {
						ToolExpressParam pnew = new ToolExpressParam();
						pnew.setOrderNumber(p.getOrderNumber());
						pnew.setV1(p.getOutNumber());
						pnew.setV3(p.getV2());
						pnew.setV4(p.getV3());
						pnew.setV5(p.getV4());
						pnew.setV6(p.getV5());
						pnew.setV7(p.getV6());
						pnew.setV8(p.getV7());
						
						List<ToolExpressParam> newlist = new ArrayList<ToolExpressParam>();
						
						ToolExpressParam plistnew = new ToolExpressParam();
						plistnew.setGoodsNumber(p.getGoodsNumber());
						plistnew.setNum(p.getNum());
						
						newlist.add(plistnew);
						pnew.setList(newlist);
						
						listadd.add(pnew);
					}
				}

		        ToolGoodsInstallParam installParam = new ToolGoodsInstallParam();
		        installParam.setCustomerId(toolWorkParam.getCustomerId());
		        installParam.setDeptId(user.getDeptId());
		        List<ToolGoodsInstallResult> listin = toolGoodsInstallService.findListBySpec(installParam,user.getOperateId());//查询品类的重量
				List<ToolExpressParam> add = new ArrayList<ToolExpressParam>();
		        for (ToolExpressParam p : listadd) {
		        	ToolExpressParam addp = new ToolExpressParam();
		        	addp.setOrderNumber(p.getOrderNumber());
		        	addp.setV1(p.getV1());
		        	addp.setV3(p.getV3());
		        	addp.setV4(p.getV4());
		        	addp.setV5(p.getV5());
		        	addp.setV6(p.getV6());
		        	addp.setV7(p.getV7());
		        	addp.setV8(p.getV8());
		        	BigDecimal snum = new BigDecimal(0);
		        	BigDecimal weightsum = new BigDecimal(0);
		        	String goodsnumber = "";
		        	for (ToolExpressParam p2 : p.getList()) {
		            	BigDecimal snum2 = new BigDecimal(p2.getNum());
		        		snum = snum.add(snum2);
		        		goodsnumber += p2.getGoodsNumber()+"*"+p2.getNum().replace(".0", "")+"，";
		        		for (ToolGoodsInstallResult in : listin) {
							if(p2.getGoodsNumber().equals(in.getGoodsNumber())) {
				            	BigDecimal weight = new BigDecimal(in.getWeight());
				            	BigDecimal weights = weight.multiply(snum2).setScale(3, BigDecimal.ROUND_HALF_DOWN);//计算重量
				            	weightsum = weightsum.add(weights);
				            	break;
							}
						}
					}
		        	addp.setNum(snum.setScale( 0, BigDecimal.ROUND_HALF_DOWN )+"");
		        	addp.setGoodsNumber(goodsnumber);
		        	addp.setWaveId(toolWorkParam.getWaveId());
		        	addp.setWellen(toolWorkParam.getWellen());
		        	addp.setCustomerId(toolWorkParam.getCustomerId());
		        	addp.setCustomerName(basicCustomer.getCustomerName());
		        	addp.setDeptId(user.getDeptId());
		        	addp.setV2(weightsum+"");
		        	add.add(addp);
				}
		        if(add.size()>0) {
		        	toolExpressService.saveBatchList(add);
		        }
		        
				ToolExpressParam expressParam = new ToolExpressParam();
				expressParam.setWaveId(toolWorkParam.getWaveId());
				expressParam.setCustomerId(toolWorkParam.getCustomerId());
				List<ToolExpressResult> list2 = toolExpressService.findListBySpecSum(expressParam);
				int z = 1;
				List<ToolExpressSumParam> listadd2 = new ArrayList<ToolExpressSumParam>();
				for (ToolExpressResult r : list2) {
					ToolExpressSumParam sumParam = new ToolExpressSumParam();
					sumParam.setWaveId(toolWorkParam.getWaveId());
					sumParam.setCustomerId(r.getCustomerId());
					sumParam.setCustomerName(r.getCustomerName());
					sumParam.setGoodsNumber(r.getGoodsNumber());
					sumParam.setNum(r.getNum()+"");
					sumParam.setOrderNum(r.getV1());
					sumParam.setSumNum(r.getV2());
					sumParam.setState("待配");
					sumParam.setV1(z+"");
					sumParam.setV2(r.getV1());
					sumParam.setDeptId(r.getDeptId());
					listadd2.add(sumParam);
					z++;
				}
				if(listadd2.size()>0) {
					ToolExpressSumParam ToolExpressSumParamdelete = new ToolExpressSumParam();
					ToolExpressSumParamdelete.setWaveId(toolWorkParam.getWaveId());
					ToolExpressSumParamdelete.setCustomerId(toolWorkParam.getCustomerId());
					toolExpressSumService.deleteBySpec(ToolExpressSumParamdelete);
					toolExpressSumService.saveBatchList(listadd2);
				}

		    	//保存已配明细
				List<ToolExpressScanParam> scanlist = new ArrayList<ToolExpressScanParam>();
				for (String str : strs) {
					ToolExpressScanParam addScanParam = new ToolExpressScanParam();
					addScanParam.setState("待更新");
					addScanParam.setWaveId(toolWorkParam.getWaveId());
					addScanParam.setOrderNumber(str);
					addScanParam.setHandover(toolWorkParam.getHandover());//交接次数
					addScanParam.setV1(toolWorkParam.getWellen());//波次
					addScanParam.setV2(toolWorkParam.getDirect());//类型
					addScanParam.setV3(toolWorkParam.getPackNumber());//包材
					scanlist.add(addScanParam);
				}
		        if(scanlist.size()>0) {
		        	toolExpressScanService.saveBatchList(scanlist);
		        }
		        toolWorkParam.setState("待派工");
		        toolWorkParam.setDeptId(user.getDeptId());
		        toolWorkParam.setDeliverId(user.getDeliverId());
		        toolWorkParam.setCustomerName(basicCustomer.getCustomerName());
		        toolWorkParam.setCreateName(user.getName());
		        toolWorkParam.setArrangeNumber(null);
		        toolWorkParam.setUserName(null);
		        this.toolWorkService.add(toolWorkParam);
			} 
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return resdata;
    }
    
    /**
     * 保存波次并派工
     * @throws InterruptedException 
     */
    @RequestMapping("/addItem")
    @ResponseBody
	@Transactional(rollbackFor = Exception.class,timeout = 600)
    public ResponseData addItem(ToolWorkParam toolWorkParam,String orderNumber) throws InterruptedException {
    	User user = userService.getcurrentUser();
    	ResponseData resdata = new ResponseData();
    	resdata.setSuccess(true);
    	
    	if(ToolUtil.isEmpty(orderNumber)) {
    		return ResponseData.error("快递单号不得为空");
    	}
    	
    	if(ToolUtil.isEmpty(toolWorkParam.getArrangeNumber())||ToolUtil.isEmpty(toolWorkParam.getUserName())) {
    		return ResponseData.error("请输入作业小组和小组人员");
    	}
    	
    	ToolWave toolWave = toolWaveService.getById(toolWorkParam.getWaveId());
    	BasicCustomer basicCustomer = basicCustomerService.getById(toolWorkParam.getCustomerId());
    	if(ToolUtil.isEmpty(basicCustomer.getJustAppkey())) {
    		return ResponseData.error("请添加客户聚水潭appKey");
    	} 
    	if(ToolUtil.isEmpty(basicCustomer.getJustAppsecret())) {
    		return ResponseData.error("请添加客户聚水潭appSecret");
    	} 
    	if(ToolUtil.isEmpty(basicCustomer.getAccessTokenme())) {
    		return ResponseData.error("请添加我方聚水潭授权码");
    	} 
    	if(ToolUtil.isEmpty(basicCustomer.getOwnercoId())) {
    		return ResponseData.error("请添加客户聚水潭货主编码");
    	} 
    	
    	String[] strs = orderNumber.split("\n");//快递单号
    	List<String> l_ids = new ArrayList<>();
    	
		lock.lock();//获取锁
		try {
			List<ToolExpressExcelParam> list = new ArrayList<ToolExpressExcelParam>();
			for (int i = 0; i < strs.length; i++) {
				l_ids.add("'"+strs[i]+"'");
				if (l_ids.size() == 20) {//最多20个快递单号获取一次
					//接口调用频率秒级内不超过5次，分钟内不超过100次
					String data = justGetXSCKDApi.getSellerItem(basicCustomer.getJustAppkey(),basicCustomer.getJustAppsecret(),basicCustomer.getAccessTokenme(), l_ids, basicCustomer.getOwnercoId());
					JSONObject jsonObject = new JSONObject(data);
					if(jsonObject.get("code").toString().equals("0")) {
						JSONObject jsonObject1 = new JSONObject(jsonObject.get("data").toString());
						if(Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {
							JSONArray jsonArray = new JSONArray(jsonObject1.get("datas").toString());
							for (Object object : jsonArray) {
								JSONObject jsonObject2 = new JSONObject(object.toString());
								JSONArray jsonArray1 = new JSONArray(jsonObject2.get("items").toString());
								for (Object object1 : jsonArray1) {
									JSONObject jsonObject3 = new JSONObject(object1.toString());
									ToolExpressExcelParam toolExpressExcelParam = new ToolExpressExcelParam();
									toolExpressExcelParam.setWaveId(toolWorkParam.getWaveId());
									toolExpressExcelParam.setWellen(toolWorkParam.getWellen());
									toolExpressExcelParam.setCustomerId(toolWorkParam.getCustomerId());
									toolExpressExcelParam.setCustomerName(basicCustomer.getCustomerName());
									toolExpressExcelParam.setDeptId(user.getDeptId());
									
									String sku_id = jsonObject3.get("sku_id").toString();
									if (ToolUtil.isNotEmpty(sku_id)) {
										if(sku_id.equals("null")||sku_id.equals("1759947952444423")||sku_id.equals("1759325202211891")||sku_id.equals("4967199140507")||sku_id.equals("1759325202211890")
												||sku_id.equals("1759947952444420")||sku_id.equals("687374017518")||sku_id.equals("693717971892")
												||sku_id.equals("caixiang")
												||sku_id.equals("qipaodai-05")
												||sku_id.equals("goodcard5")
												||sku_id.equals("goodcard2")
												||sku_id.equals("TM-R0")||sku_id.equals("TM-NK")
												||sku_id.equals("TM-RO")
												||sku_id.equals("zhixiang")||sku_id.equals("zhixiang-A1")||sku_id.equals("zhixiang-A3")
												||sku_id.equals("会员福利卡")||sku_id.equals("瑜大公子卡片")||sku_id.equals("纸箱包装")) {
											continue;
										}
										toolExpressExcelParam.setGoodsNumber(sku_id);//商品编号
									}
									
									String num = jsonObject3.get("qty").toString();
									if (ToolUtil.isNotEmpty(num)) {
										if(num.equals("null")) {
											continue;
										} else {
											toolExpressExcelParam.setNum(num);//数量
										}
									} else {
										continue;
									}
									
									String v1 = jsonObject2.get("io_id").toString();
									if (ToolUtil.isNotEmpty(v1)) {
										if(!v1.equals("null")) {
											toolExpressExcelParam.setOutNumber(v1);//出库单号
										} else {
											continue;
										}
									} else {
										continue;
									}
									
									String  l_id = jsonObject2.get("l_id").toString();
									if (ToolUtil.isNotEmpty(l_id)) {
										if(!l_id.equals("null")) {
											toolExpressExcelParam.setOrderNumber(l_id);//快递单号
										} 
									}
									
									String v2 = jsonObject2.get("logistics_company").toString();
									if (ToolUtil.isNotEmpty(v2)) {
										if(!v2.equals("null")) {
											toolExpressExcelParam.setV2(v2);//快递公司
										} 
									}
									
									String v3 = jsonObject2.get("receiver_state").toString();
									if (ToolUtil.isNotEmpty(v3)) {
										if(!v3.equals("null")) {
											toolExpressExcelParam.setV3(v3);//省份
										} 
									}
									
									String v4 = jsonObject2.get("receiver_city").toString();
									if (ToolUtil.isNotEmpty(v4)) {
										if(!v4.equals("null")) {
											toolExpressExcelParam.setV4(v4);//城市
										} 
									}
									
									String v5 = jsonObject2.get("receiver_district").toString();
									if (ToolUtil.isNotEmpty(v5)) {
										if(!v5.equals("null")) {
											toolExpressExcelParam.setV5(v5);//区县
										} 
									}
									
									String v6 = jsonObject2.get("receiver_town").toString();
									if (ToolUtil.isNotEmpty(v6)) {
										if(!v6.equals("null")) {
											toolExpressExcelParam.setV6(v6);//街道
										} 
									}
									
									String v7 = "";
									if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV3())) {
										v7 += toolExpressExcelParam.getV3();
										if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV4())) {
											v7 += toolExpressExcelParam.getV4();
											if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV5())) {
												v7 += toolExpressExcelParam.getV5();
												if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV6())) {
													v7 += toolExpressExcelParam.getV6();
												}
											}
										}
									}
									toolExpressExcelParam.setV7(v7);
									
									list.add(toolExpressExcelParam);
								}
							}
						} else {
							resdata.setSuccess(false);
							resdata.setMessage("未获取到快递明细");
						}
					} else {
						resdata.setSuccess(false);
						resdata.setMessage("拉取失败！"+data);
					}
					if((i+1) < strs.length) {
						Thread.currentThread().sleep(210);//如果有下一页 等待0.21秒
					}
					l_ids = new ArrayList<>();
				}
			}
			
			if(l_ids.size() > 0) {
				String data = justGetXSCKDApi.getSellerItem(basicCustomer.getJustAppkey(),basicCustomer.getJustAppsecret(),basicCustomer.getAccessTokenme(), l_ids, basicCustomer.getOwnercoId());
				JSONObject jsonObject = new JSONObject(data);
				if(jsonObject.get("code").toString().equals("0")) {
					JSONObject jsonObject1 = new JSONObject(jsonObject.get("data").toString());
					if(Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {
						JSONArray jsonArray = new JSONArray(jsonObject1.get("datas").toString());
						for (Object object : jsonArray) {
							JSONObject jsonObject2 = new JSONObject(object.toString());
							JSONArray jsonArray1 = new JSONArray(jsonObject2.get("items").toString());
							for (Object object1 : jsonArray1) {
								JSONObject jsonObject3 = new JSONObject(object1.toString());
								ToolExpressExcelParam toolExpressExcelParam = new ToolExpressExcelParam();
								toolExpressExcelParam.setWaveId(toolWorkParam.getWaveId());
								toolExpressExcelParam.setWellen(toolWorkParam.getWellen());
								toolExpressExcelParam.setCustomerId(toolWorkParam.getCustomerId());
								toolExpressExcelParam.setCustomerName(basicCustomer.getCustomerName());
								toolExpressExcelParam.setDeptId(user.getDeptId());
								
								String sku_id = jsonObject3.get("sku_id").toString();
								if (ToolUtil.isNotEmpty(sku_id)) {
									if(sku_id.equals("null")||sku_id.equals("1759947952444423")||sku_id.equals("1759325202211891")||sku_id.equals("4967199140507")||sku_id.equals("1759325202211890")
											||sku_id.equals("1759947952444420")||sku_id.equals("687374017518")||sku_id.equals("693717971892")
											||sku_id.equals("caixiang")
											||sku_id.equals("qipaodai-05")
											||sku_id.equals("goodcard5")
											||sku_id.equals("goodcard2")
											||sku_id.equals("TM-R0")||sku_id.equals("TM-NK")
											||sku_id.equals("TM-RO")
											||sku_id.equals("zhixiang")||sku_id.equals("zhixiang-A1")||sku_id.equals("zhixiang-A3")
											||sku_id.equals("会员福利卡")||sku_id.equals("瑜大公子卡片")||sku_id.equals("纸箱包装")) {
										continue;
									}
									toolExpressExcelParam.setGoodsNumber(sku_id);//商品编号
								}
								
								String num = jsonObject3.get("qty").toString();
								if (ToolUtil.isNotEmpty(num)) {
									if(num.equals("null")) {
										continue;
									} else {
										toolExpressExcelParam.setNum(num);//数量
									}
								} else {
									continue;
								}
								
								String v1 = jsonObject2.get("io_id").toString();
								if (ToolUtil.isNotEmpty(v1)) {
									if(!v1.equals("null")) {
										toolExpressExcelParam.setOutNumber(v1);//出库单号
									} else {
										continue;
									}
								} else {
									continue;
								}
								
								String  l_id = jsonObject2.get("l_id").toString();
								if (ToolUtil.isNotEmpty(l_id)) {
									if(!l_id.equals("null")) {
										toolExpressExcelParam.setOrderNumber(l_id);//快递单号
									} 
								}
								
								String v2 = jsonObject2.get("logistics_company").toString();
								if (ToolUtil.isNotEmpty(v2)) {
									if(!v2.equals("null")) {
										toolExpressExcelParam.setV2(v2);//快递公司
									} 
								}
								
								String v3 = jsonObject2.get("receiver_state").toString();
								if (ToolUtil.isNotEmpty(v3)) {
									if(!v3.equals("null")) {
										toolExpressExcelParam.setV3(v3);//省份
									} 
								}
								
								String v4 = jsonObject2.get("receiver_city").toString();
								if (ToolUtil.isNotEmpty(v4)) {
									if(!v4.equals("null")) {
										toolExpressExcelParam.setV4(v4);//城市
									} 
								}
								
								String v5 = jsonObject2.get("receiver_district").toString();
								if (ToolUtil.isNotEmpty(v5)) {
									if(!v5.equals("null")) {
										toolExpressExcelParam.setV5(v5);//区县
									} 
								}
								
								String v6 = jsonObject2.get("receiver_town").toString();
								if (ToolUtil.isNotEmpty(v6)) {
									if(!v6.equals("null")) {
										toolExpressExcelParam.setV6(v6);//街道
									} 
								}
								
								String v7 = "";
								if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV3())) {
									v7 += toolExpressExcelParam.getV3();
									if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV4())) {
										v7 += toolExpressExcelParam.getV4();
										if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV5())) {
											v7 += toolExpressExcelParam.getV5();
											if(ToolUtil.isNotEmpty(toolExpressExcelParam.getV6())) {
												v7 += toolExpressExcelParam.getV6();
											}
										}
									}
								}
								toolExpressExcelParam.setV7(v7);
								
								list.add(toolExpressExcelParam);
							}
						}
					} else {
						resdata.setSuccess(false);
						resdata.setMessage("未获取到快递明细");
					}
				} else {
					resdata.setSuccess(false);
					resdata.setMessage("拉取失败！"+data);
				}
			}
			
			if(list.size()>0) {
		        toolExpressExcelService.saveBatchList(list);

				List<ToolExpressParam> listadd = new ArrayList<ToolExpressParam>();
		        for (ToolExpressExcelParam p : list) {
					boolean order = false;
					for (int i = 0; i < listadd.size(); i++) {
						if(listadd.get(i).getV1().equals(p.getOutNumber())) {
							order = true;
							boolean goods = false;
							for (ToolExpressParam tp2 : listadd.get(i).getList()) {
								if(tp2.getGoodsNumber().equals(p.getGoodsNumber())){
									goods = true;
									BigDecimal num = new BigDecimal(tp2.getNum());
									BigDecimal nump = new BigDecimal(p.getNum());
									tp2.setNum(num.add(nump)+"");
									break;
								}
							}
							if(!goods) {
								ToolExpressParam pnew = new ToolExpressParam();
								pnew.setGoodsNumber(p.getGoodsNumber());
								pnew.setNum(p.getNum());
								listadd.get(i).getList().add(pnew);
								break;
							} else {
								break;
							}
						}
					}
					if(!order) {
						ToolExpressParam pnew = new ToolExpressParam();
						pnew.setOrderNumber(p.getOrderNumber());
						pnew.setV1(p.getOutNumber());
						pnew.setV3(p.getV2());
						pnew.setV4(p.getV3());
						pnew.setV5(p.getV4());
						pnew.setV6(p.getV5());
						pnew.setV7(p.getV6());
						pnew.setV8(p.getV7());
						
						List<ToolExpressParam> newlist = new ArrayList<ToolExpressParam>();
						
						ToolExpressParam plistnew = new ToolExpressParam();
						plistnew.setGoodsNumber(p.getGoodsNumber());
						plistnew.setNum(p.getNum());
						
						newlist.add(plistnew);
						pnew.setList(newlist);
						
						listadd.add(pnew);
					}
				}

		        ToolGoodsInstallParam installParam = new ToolGoodsInstallParam();
		        installParam.setCustomerId(toolWorkParam.getCustomerId());
		        installParam.setDeptId(user.getDeptId());
		        List<ToolGoodsInstallResult> listin = toolGoodsInstallService.findListBySpec(installParam,user.getOperateId());//查询品类的重量
				List<ToolExpressParam> add = new ArrayList<ToolExpressParam>();
		        for (ToolExpressParam p : listadd) {
		        	ToolExpressParam addp = new ToolExpressParam();
		        	addp.setOrderNumber(p.getOrderNumber());
		        	addp.setV1(p.getV1());
		        	addp.setV3(p.getV3());
		        	addp.setV4(p.getV4());
		        	addp.setV5(p.getV5());
		        	addp.setV6(p.getV6());
		        	addp.setV7(p.getV7());
		        	addp.setV8(p.getV8());
		        	BigDecimal snum = new BigDecimal(0);
		        	BigDecimal weightsum = new BigDecimal(0);
		        	String goodsnumber = "";
		        	for (ToolExpressParam p2 : p.getList()) {
		            	BigDecimal snum2 = new BigDecimal(p2.getNum());
		        		snum = snum.add(snum2);
		        		goodsnumber += p2.getGoodsNumber()+"*"+p2.getNum().replace(".0", "")+"，";
		        		for (ToolGoodsInstallResult in : listin) {
							if(p2.getGoodsNumber().equals(in.getGoodsNumber())) {
				            	BigDecimal weight = new BigDecimal(in.getWeight());
				            	BigDecimal weights = weight.multiply(snum2).setScale(3, BigDecimal.ROUND_HALF_DOWN);//计算重量
				            	weightsum = weightsum.add(weights);
				            	break;
							}
						}
					}
		        	addp.setNum(snum.setScale( 0, BigDecimal.ROUND_HALF_DOWN )+"");
		        	addp.setGoodsNumber(goodsnumber);
		        	addp.setWaveId(toolWorkParam.getWaveId());
		        	addp.setWellen(toolWorkParam.getWellen());
		        	addp.setCustomerId(toolWorkParam.getCustomerId());
		        	addp.setCustomerName(basicCustomer.getCustomerName());
		        	addp.setDeptId(user.getDeptId());
		        	addp.setV2(weightsum+"");
		        	add.add(addp);
				}
		        if(add.size()>0) {
		        	toolExpressService.saveBatchList(add);
		        }
		        
				ToolExpressParam expressParam = new ToolExpressParam();
				expressParam.setWaveId(toolWorkParam.getWaveId());
				expressParam.setCustomerId(toolWorkParam.getCustomerId());
				List<ToolExpressResult> list2 = toolExpressService.findListBySpecSum(expressParam);
				int z = 1;
				List<ToolExpressSumParam> listadd2 = new ArrayList<ToolExpressSumParam>();
				for (ToolExpressResult r : list2) {
					ToolExpressSumParam sumParam = new ToolExpressSumParam();
					sumParam.setWaveId(toolWorkParam.getWaveId());
					sumParam.setCustomerId(r.getCustomerId());
					sumParam.setCustomerName(r.getCustomerName());
					sumParam.setGoodsNumber(r.getGoodsNumber());
					sumParam.setNum(r.getNum()+"");
					sumParam.setOrderNum(r.getV1());
					sumParam.setSumNum(r.getV2());
					sumParam.setState("待配");
					sumParam.setV1(z+"");
					sumParam.setV2(r.getV1());
					sumParam.setDeptId(r.getDeptId());
					listadd2.add(sumParam);
					z++;
				}
				if(listadd2.size()>0) {
					ToolExpressSumParam ToolExpressSumParamdelete = new ToolExpressSumParam();
					ToolExpressSumParamdelete.setWaveId(toolWorkParam.getWaveId());
					ToolExpressSumParamdelete.setCustomerId(toolWorkParam.getCustomerId());
					toolExpressSumService.deleteBySpec(ToolExpressSumParamdelete);
					toolExpressSumService.saveBatchList(listadd2);
				}

		    	ToolTaskArrangeParam taskArrangeParam = new ToolTaskArrangeParam();
		    	taskArrangeParam.setWaveId(toolWorkParam.getWaveId());
		    	taskArrangeParam.setGroupNumber(toolWorkParam.getArrangeNumber());
		    	taskArrangeParam.setGroupUsers(toolWorkParam.getUserName());
		    	ToolTaskArrangeResult arrangeResult = toolTaskArrangeService.findBySpec(taskArrangeParam);
		    	if(arrangeResult != null) {
		    		toolWorkParam.setArrangeId(Long.parseLong(arrangeResult.getId().toString()));
		    	} else {
		    		taskArrangeParam.setTaskDate(toolWave.getWaveName());
		    		taskArrangeParam.setGroupUsers(toolWorkParam.getUserName());
		    		taskArrangeParam.setDeptId(user.getDeptId());
		    		taskArrangeParam.setDeliverId(user.getDeliverId());
		    		taskArrangeParam.setCreateTime(new Date());
		    		taskArrangeParam.setCreateUserName(user.getName());
		    		toolTaskArrangeService.addReturnId(taskArrangeParam);
		    		toolWorkParam.setArrangeId(Long.parseLong(taskArrangeParam.getId().toString()));
		    	}

		    	//保存已配明细
				List<ToolExpressScanParam> scanlist = new ArrayList<ToolExpressScanParam>();
				for (String str : strs) {
					ToolExpressScanParam addScanParam = new ToolExpressScanParam();
					addScanParam.setState("待更新");
					addScanParam.setWaveId(toolWorkParam.getWaveId());
					addScanParam.setOrderNumber(str);
					addScanParam.setArrangeId(toolWorkParam.getArrangeId());
					addScanParam.setArrangeNumber(toolWorkParam.getArrangeNumber());
					addScanParam.setUserName(toolWorkParam.getUserName());
					addScanParam.setHandover(toolWorkParam.getHandover());
					addScanParam.setV1(toolWorkParam.getWellen());//波次
					addScanParam.setV2(toolWorkParam.getDirect());
					addScanParam.setV3(toolWorkParam.getPackNumber());
					scanlist.add(addScanParam);
				}
		        if(scanlist.size()>0) {
		        	toolExpressScanService.saveBatchList(scanlist);
		        }
		        
		        toolWorkParam.setState("已完成");
		        toolWorkParam.setCustomerName(basicCustomer.getCustomerName());
		        toolWorkParam.setCreateName(user.getName());
		        toolWorkParam.setDeptId(user.getDeptId());
		        toolWorkParam.setDeptId(user.getDeliverId());
		        this.toolWorkService.addReturnId(toolWorkParam);
		    	
		        if(toolWorkParam.getAddTask().equals("是")) {
			    	BasicPositionParam positionParam = new BasicPositionParam();
			    	positionParam.setPositionNumber(toolWorkParam.getArrangeNumber());
			    	BasicPositionResult positionResult = basicPositionService.findBySpec(positionParam, user.getDeptId(), user.getOperateId());
			    	if(positionResult == null) {
			            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
			    		return ResponseData.error(toolWorkParam.getArrangeNumber()+"库位不存在");
			    	}
			    	
		        	ToolExpressExcelParam sumExcelParam = new ToolExpressExcelParam();
		        	sumExcelParam.setWaveId(toolWorkParam.getWaveId());
		        	sumExcelParam.setCustomerId(toolWorkParam.getCustomerId());
		        	sumExcelParam.setWellen(toolWorkParam.getWellen());
		        	List<ToolExpressExcelResult> sumExcellist = toolExpressExcelService.findSumListBySpec2(sumExcelParam);//合计波次商品
			    	
		        	List<ToolWorkTaskParam> workTaskList = new ArrayList<ToolWorkTaskParam>();
		        	for (ToolExpressExcelResult r : sumExcellist) {
		        		BasicGoodsParam goodsParam = new BasicGoodsParam();
		        		goodsParam.setGoodsNumber(r.getGoodsNumber());
		        		goodsParam.setGoodsCustomerId(Integer.parseInt(toolWorkParam.getCustomerId().toString()));
		        		BasicGoodsResult goodsResult = basicGoodsService.findBySpec(goodsParam, null);
		        		if(goodsResult == null) {
				            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				    		return ResponseData.error(r.getGoodsNumber()+"商品不存在");
		        		}
		        		
		        		ToolWorkTaskParam addTaskParam = new ToolWorkTaskParam();
		        		addTaskParam.setWaveId(toolWorkParam.getWaveId());
		        		addTaskParam.setWorkId(Long.parseLong(toolWorkParam.getId().toString()));
		        		addTaskParam.setState("补货中");
		        		addTaskParam.setCustomerId(toolWorkParam.getCustomerId());
		        		addTaskParam.setCustomerName(toolWorkParam.getCustomerName());
		        		addTaskParam.setWellen(toolWorkParam.getWellen());
		        		addTaskParam.setPositionId(Long.parseLong(positionResult.getId().toString()));
		        		addTaskParam.setPositionNumber(positionResult.getPositionNumber());
		        		addTaskParam.setGoodsName(goodsResult.getGoodsName());
		        		addTaskParam.setGoodsNumber(r.getGoodsNumber());
		        		addTaskParam.setGoodsId(Long.parseLong(goodsResult.getId().toString()));
		        		addTaskParam.setNum(r.getNum());
		        		addTaskParam.setStayNum(r.getNum());
		        		addTaskParam.setAlreadyNum("0");
		        		addTaskParam.setDeptId(user.getDeptId());
		        		addTaskParam.setDeliverId(user.getDeliverId());
		        		addTaskParam.setCreateTime(new Date());
		        		addTaskParam.setCreateName(user.getName());
		        		workTaskList.add(addTaskParam);
					}
		        	if(workTaskList.size()>0) {
		        		toolWorkTaskService.saveBatchList(workTaskList);
		        	}
		        }
			} 
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return resdata;
    }

    @Autowired
    private BasicGoodsService basicGoodsService;

    @Autowired
    private BasicPositionService basicPositionService;

    @Autowired
    private ToolWorkTaskService toolWorkTaskService;

    @Autowired
    private ToolExpressScanService toolExpressScanService;

    @Autowired
    private ToolTaskArrangeService toolTaskArrangeService;
    
    @Autowired
    private ToolExpressExcelService toolExpressExcelService;

    @Autowired
    private ToolExpressService toolExpressService;

    @Autowired
    private ToolGoodsInstallService toolGoodsInstallService;

    @Autowired
    private ToolExpressSumService toolExpressSumService;

    /**
     *派工接口
     */
    @RequestMapping("/addWork")
    @ResponseBody
	@Transactional(rollbackFor = Exception.class,timeout = 600)
    public ResponseData addWork(ToolWorkParam toolWorkParam,Integer[] ids) {
    	if(ToolUtil.isEmpty(toolWorkParam.getArrangeNumber())) {
    		return ResponseData.error("小组编号不得为空");
    	}
    	User user = userService.getcurrentUser();
    	ToolWave toolWave = toolWaveService.getById(toolWorkParam.getWaveId());
    	ToolTaskArrangeParam taskArrangeParam = new ToolTaskArrangeParam();
    	taskArrangeParam.setWaveId(toolWorkParam.getWaveId());
    	taskArrangeParam.setGroupNumber(toolWorkParam.getArrangeNumber());
    	taskArrangeParam.setGroupUsers(toolWorkParam.getUserName());
    	ToolTaskArrangeResult arrangeResult = toolTaskArrangeService.findBySpec(taskArrangeParam);
    	if(arrangeResult != null) {
    		toolWorkParam.setArrangeId(Long.parseLong(arrangeResult.getId().toString()));
    	} else {
    		taskArrangeParam.setTaskDate(toolWave.getWaveName());
    		taskArrangeParam.setGroupUsers(toolWorkParam.getUserName());
    		taskArrangeParam.setDeptId(user.getDeptId());
    		taskArrangeParam.setDeliverId(user.getDeliverId());
    		taskArrangeParam.setCreateTime(new Date());
    		taskArrangeParam.setCreateUserName(user.getName());
    		toolTaskArrangeService.addReturnId(taskArrangeParam);
    		toolWorkParam.setArrangeId(Long.parseLong(taskArrangeParam.getId().toString()));
    	}
    	for (Integer id : ids) {
    		ToolWork toolWork = toolWorkService.getById(id);
            if(toolWork.getAddTask().equals("是")) {
    	    	BasicPositionParam positionParam = new BasicPositionParam();
    	    	positionParam.setPositionNumber(toolWorkParam.getArrangeNumber());
    	    	BasicPositionResult positionResult = basicPositionService.findBySpec(positionParam, user.getDeptId(), user.getOperateId());
    	    	if(positionResult == null) {
    	            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
    	    		return ResponseData.error(toolWorkParam.getArrangeNumber()+"库位不存在");
    	    	}
    	    	
            	ToolExpressExcelParam sumExcelParam = new ToolExpressExcelParam();
            	sumExcelParam.setWaveId(toolWork.getWaveId());
            	sumExcelParam.setCustomerId(toolWork.getCustomerId());
            	sumExcelParam.setWellen(toolWork.getWellen());
            	List<ToolExpressExcelResult> sumExcellist = toolExpressExcelService.findSumListBySpec2(sumExcelParam);//合计波次商品
    	    	
            	List<ToolWorkTaskParam> workTaskList = new ArrayList<ToolWorkTaskParam>();
            	for (ToolExpressExcelResult r : sumExcellist) {
            		BasicGoodsParam goodsParam = new BasicGoodsParam();
            		goodsParam.setGoodsNumber(r.getGoodsNumber());
            		goodsParam.setGoodsCustomerId(Integer.parseInt(toolWork.getCustomerId().toString()));
            		BasicGoodsResult goodsResult = basicGoodsService.findBySpec(goodsParam, null);
            		if(goodsResult == null) {
    		            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
    		    		return ResponseData.error(r.getGoodsNumber()+"商品不存在");
            		}
            		
            		ToolWorkTaskParam addTaskParam = new ToolWorkTaskParam();
            		addTaskParam.setWaveId(toolWork.getWaveId());
            		addTaskParam.setWorkId(Long.parseLong(toolWork.getId().toString()));
            		addTaskParam.setState("补货中");
            		addTaskParam.setCustomerId(toolWork.getCustomerId());
            		addTaskParam.setCustomerName(toolWork.getCustomerName());
            		addTaskParam.setWellen(toolWork.getWellen());
            		addTaskParam.setPositionId(Long.parseLong(positionResult.getId().toString()));
            		addTaskParam.setPositionNumber(positionResult.getPositionNumber());
            		addTaskParam.setGoodsName(goodsResult.getGoodsName());
            		addTaskParam.setGoodsNumber(r.getGoodsNumber());
            		addTaskParam.setGoodsId(Long.parseLong(goodsResult.getId().toString()));
            		addTaskParam.setNum(r.getNum());
	        		addTaskParam.setStayNum(r.getNum());
	        		addTaskParam.setAlreadyNum("0");
	        		addTaskParam.setDeptId(user.getDeptId());
	        		addTaskParam.setDeliverId(user.getDeliverId());
            		addTaskParam.setCreateTime(new Date());
            		addTaskParam.setCreateName(user.getName());
            		workTaskList.add(addTaskParam);
    			}
            	if(workTaskList.size()>0) {
            		toolWorkTaskService.saveBatchList(workTaskList);
            	}
            }
            
    		ToolWorkParam workUpadate = new ToolWorkParam();
    		workUpadate.setId(id);
    		workUpadate.setState("已完成");
    		workUpadate.setArrangeId(toolWorkParam.getArrangeId());
    		workUpadate.setArrangeNumber(toolWorkParam.getArrangeNumber());
    		workUpadate.setUserName(toolWorkParam.getUserName());
    		this.toolWorkService.update(workUpadate);
    		
    		ToolExpressScanParam scanUpdate = new ToolExpressScanParam();
    		scanUpdate.setWaveId(toolWork.getWaveId());
    		scanUpdate.setArrangeId(toolWorkParam.getArrangeId());
    		scanUpdate.setArrangeNumber(toolWorkParam.getArrangeNumber());
    		scanUpdate.setUserName(toolWorkParam.getUserName());
    		scanUpdate.setV1(toolWork.getWellen());
    		toolExpressScanService.updateArrangeBySpec(scanUpdate);
		}
        return ResponseData.success();
    }

    /**
     * 编辑接口
     * @author zhucx
     * @Date 2023-04-18
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(ToolWorkParam toolWorkParam) {
        this.toolWorkService.update(toolWorkParam);
    	
    	ToolExpressScanParam toolExpressScanParam = new ToolExpressScanParam();
    	toolExpressScanParam.setWaveId(toolWorkParam.getWaveId());
    	toolExpressScanParam.setV1(toolWorkParam.getWellen());
    	toolExpressScanParam.setHandover(toolWorkParam.getHandover());
    	toolExpressScanParam.setV2(toolWorkParam.getDirect());
    	toolExpressScanParam.setV3(toolWorkParam.getPackNumber());
    	toolExpressScanService.updateBySpec(toolExpressScanParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author zhucx
     * @Date 2023-04-18
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(ToolWorkParam toolWorkParam) {
    	ToolWork toolWork = toolWorkService.getById(toolWorkParam.getId());
        this.toolWorkService.delete(toolWorkParam);
        
        ToolWorkTaskParam toolWorkTaskParam = new ToolWorkTaskParam();
        toolWorkTaskParam.setWorkId(Long.parseLong(toolWorkParam.getId().toString()));
        toolWorkTaskParam.setState("补货中");
        List<ToolWorkTaskResult> tasklist = toolWorkTaskService.findListBySpec(toolWorkTaskParam);
		BigDecimal as = new BigDecimal("0");
        for (ToolWorkTaskResult r : tasklist) {
			BigDecimal alreadyNum = new BigDecimal(r.getAlreadyNum());
			if(alreadyNum.compareTo(as) == 0) {
		        ToolWorkTaskParam deleteToolWorkTaskParam = new ToolWorkTaskParam();
		        deleteToolWorkTaskParam.setId(r.getId());
				toolWorkTaskService.delete(deleteToolWorkTaskParam);
			}
		}
        
        ToolExpressScanParam toolExpressScanParam = new ToolExpressScanParam();
        toolExpressScanParam.setWaveId(toolWork.getWaveId());
        toolExpressScanParam.setV1(toolWork.getWellen());
        this.toolExpressScanService.deleteBySpec(toolExpressScanParam);

        ToolExpressExcelParam toolExpressExcelParam = new ToolExpressExcelParam();
        toolExpressExcelParam.setWaveId(toolWork.getWaveId());
        toolExpressExcelParam.setWellen(toolWork.getWellen());
        toolExpressExcelService.deleteBySpec(toolExpressExcelParam);
        
        ToolExpressParam expressParam = new ToolExpressParam();
        expressParam.setWaveId(toolWork.getWaveId());
        expressParam.setWellen(toolWork.getWellen());
        toolExpressService.deleteBySpec(expressParam);

		ToolExpressParam expressParam2 = new ToolExpressParam();
		expressParam2.setWaveId(toolWork.getWaveId());
		List<ToolExpressResult> list2 = toolExpressService.findListBySpecSum(expressParam2);
		int z = 1;
		List<ToolExpressSumParam> listadd2 = new ArrayList<ToolExpressSumParam>();
		for (ToolExpressResult r : list2) {
			ToolExpressSumParam sumParam = new ToolExpressSumParam();
			sumParam.setWaveId(toolWork.getWaveId());
			sumParam.setCustomerId(r.getCustomerId());
			sumParam.setCustomerName(r.getCustomerName());
			sumParam.setGoodsNumber(r.getGoodsNumber());
			sumParam.setNum(r.getNum()+"");
			sumParam.setOrderNum(r.getV1());
			sumParam.setSumNum(r.getV2());
			sumParam.setState("待配");
			sumParam.setV1(z+"");
			sumParam.setV2(r.getV1());
			sumParam.setDeptId(r.getDeptId());
			listadd2.add(sumParam);
			z++;
		}
		if(listadd2.size()>0) {
			ToolExpressSumParam ToolExpressSumParamdelete = new ToolExpressSumParam();
			ToolExpressSumParamdelete.setWaveId(toolWork.getWaveId());
			toolExpressSumService.deleteBySpec(ToolExpressSumParamdelete);
			toolExpressSumService.saveBatchList(listadd2);
		}
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author zhucx
     * @Date 2023-04-18
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(ToolWorkParam toolWorkParam) {
        ToolWork detail = this.toolWorkService.getById(toolWorkParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author zhucx
     * @Date 2023-04-18
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(ToolWorkParam toolWorkParam,String condition ) {
        return this.toolWorkService.findPageBySpec(toolWorkParam,condition);
    }

}


